/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"fmt"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	. "saas_sys_base/modules/merchantCard/models"
)

type MchUserMemberCardDal struct {
	// add your model here
	tbMchUserMemberCard MchUserMemberCard
	tbMchMemberCard MchMemberCard
}

//第三种实现乐观锁重试版本
func (t *MchUserMemberCardDal) AddBalance(session *lego.DbSession, userCardId int64, balanceAddend CardAddBalance) error {
	err := utils.RetryHandleForOptimisticLock(func ()  (int64, error) { //循环中重试
		s := session
		userCard := t.tbMchUserMemberCard.RecodeByIdWithsession(s.GetSession(), userCardId)
		if userCard == nil {
			return 0, fmt.Errorf("not found userCardId<%d>", userCardId)
		}

		mchCard := t.tbMchMemberCard.RecodeByIdWithsession(s.GetSession(), userCard.MchCardId)
		if mchCard == nil {
			return 0, fmt.Errorf("not found mchCard<%d>", mchCard)
		}

		userCard.Balance = userCard.Balance + balanceAddend.AddBalance
		userCard.Balance = userCard.Balance + balanceAddend.GiveBalance
		userCard.Bonus = userCard.Bonus + balanceAddend.AddBonus

		cols := []string{Feild_MchUserMemberCard.Bonus,
			             Feild_MchUserMemberCard.Balance}
		affectedRows, err := t.tbMchUserMemberCard.UpdateRecodeWithSession(s.GetSession(), userCard, cols...)
		return affectedRows, err
	})


	return err
}


func (t *MchUserMemberCardDal) AddBalance_depression(session *lego.DbSession, userCardId int64, addend int) error {
	err := utils.RetryHandle(func ()  (bool, error) { //循环中重试
		s := session
		userCard := t.tbMchUserMemberCard.RecodeByIdWithsession(s.GetSession(), userCardId)
		if userCard == nil {
			return false, fmt.Errorf("not found userCardId<%d>", userCardId)
		}

		userCard.Balance = userCard.Balance + addend
		count, err := t.tbMchUserMemberCard.UpdateRecodeWithSession(s.GetSession(), userCard)
		if err != nil {
			//s.Rollback()
			return false, err //有错误就不需要重试了
		}

		if  count <= 0 { //乐观锁：乐观锁version过期，会走到这个分支
			//s.Rollback()
			return true, err //err_const.ErrDbAffectedRowsIsZero //只有乐观锁过期需要重试，其它的不需要重试
		}


		//s.Commit()
		return false, nil //false表示不需要重试了
	})


	return err
}

//第二种实现乐观锁重试版本
func (t *MchUserMemberCardDal) AddBalance_depression2(session *lego.DbSession, userCardId int64, addend int) error {
	//err := utils.RetryHandleForErr(func ()  (error) { //循环中重试
		s := session
		userCard := t.tbMchUserMemberCard.RecodeByIdWithsession(s.GetSession(), userCardId)
		if userCard == nil {
			return fmt.Errorf("not found userCardId<%d>", userCardId)
		}

		userCard.Balance = userCard.Balance + addend
		_, err := t.tbMchUserMemberCard.UpdateRecodeWithSession(s.GetSession(), userCard)
		return err
	//}, err_const.ErrDbAffectedRowsIsZero) //如果返回ErrDbAffectedRowsIsZero就会重试，其它错误不重试


	return err
}

